package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jjn
 * @since 2022/9/7 23:12
 */
public class LeetCode1592_RearrangeSpacesBetweenWords {

    public String reorderSpaces(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }
        String[] parts = text.split("\s+");
        if (parts.length == 1) {
            return text;
        }
        List<String> words = new ArrayList<>();
        for (String part : parts) {
            if (part.length() > 0) {
                words.add(part);
            }
        }
        int spaceCount = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == ' ') {
                spaceCount++;
            }
        }
        if (words.size() == 1 && spaceCount > 0) {
            return words.get(0) + " ".repeat(spaceCount);
        }
        int averageSpaceCount = spaceCount / (words.size() - 1);
        int restSpace = spaceCount - averageSpaceCount * (words.size() - 1);
        return String.join(" ".repeat(Math.max(0, averageSpaceCount)), words) +
                " ".repeat(Math.max(0, restSpace));
    }
}
